﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sl.Support.Forms {
	public class CmdBox : TextBox {
		public CmdBox() : base() {
			Multiline = true;
			Is_Cmd_Send_clean = false;
		}
		Queue<string> cmd_queue = new Queue<string>();
		string cmd_temp;
		int cmd_queue_num = -1;
		///执行命令的函数，如果命令被接受则返回true，否则返回false
		public Func<string, bool> inputCmd;
		public bool Is_Cmd_Send_clean{get;set;}
		protected override void OnKeyDown(KeyEventArgs e) {
			if (e.KeyData == Keys.Enter) {
				e.Handled = true; 
				e.SuppressKeyPress = true;
				send();
			} else if (e.KeyData == Keys.Down) {
				e.Handled = true;
				e.SuppressKeyPress = true;
				if (cmd_queue_num < cmd_queue.Count) {
					cmd_queue_num++;
					if (cmd_queue_num < cmd_queue.Count) {
						Text = cmd_queue.ToArray()[cmd_queue_num];
					} else {
						Text = cmd_temp;
					}
				}
			} else if (e.KeyData == Keys.Up) {
				e.Handled = true;
				e.SuppressKeyPress = true;
				if (cmd_queue_num == cmd_queue.Count) {
					cmd_temp = Text;
				}
				if (cmd_queue_num > 0) {
					cmd_queue_num--;
					Text = cmd_queue.ToArray()[cmd_queue_num];
				}
			}
			base.OnKeyDown(e);
		}
		public void send() {
			if (inputCmd?.Invoke(Text) == true) {
				cmd_queue.Enqueue(Text);
				cmd_queue_num = cmd_queue.Count;
				cmd_temp = null;
				if (Is_Cmd_Send_clean) {
					this.Clear();
				} 
			}
		}
		new public void Clear() {
			if (Text != "") {
				base.Clear();
			}
		}



	}
}
